package com.telenav.framework.dao;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.telenav.framework.persistent.AbstractStore;
import com.telenav.framework.persistent.PersistentManager;
import com.telenav.module.entity.MessageEntity;


public class MessagesDao {

	private AbstractStore messagesStore;

	private static class SingletonHolder {
		public static final MessagesDao INSTANCE = new MessagesDao();
	}

	public static MessagesDao getInstance() {
		return SingletonHolder.INSTANCE;
	}

	private MessagesDao() {
		messagesStore = PersistentManager.getInstance().createStore(
				PersistentManager.DATABASE, "message_data");
		messagesStore.load();
	}

	public List<MessageEntity> getMessage(int msgId) {
		if (this.messagesStore != null) {
			byte[] messagesData = this.messagesStore.get(msgId);
			if (messagesData != null) {
				String jsonStr = new String(messagesData);
				return parseToList(jsonStr);
			}
		}
		return new ArrayList();
	}

	public void setMessage(int msgId, List<MessageEntity> messages) {
		if (messages == null)
			return;

		if (this.messagesStore != null) {
			this.messagesStore.put(msgId, convertToString(messages).getBytes());
		}
	}
	
	
	private String convertToString(List<MessageEntity> list) {
		// TODO Auto-generated method stub
		JSONArray json = new JSONArray();
		try {
			for (int j = 0; j < list.size(); j++) {
				MessageEntity msg = (MessageEntity) list.get(j);
				JSONObject jo = new JSONObject();
				jo.put("msgId", msg.getMessageid());
				jo.put("msgFrom", msg.getFrom());
				jo.put("msgDate", msg.getDate());
				jo.put("msgBody", msg.getMessage());
				json.put(jo);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json.toString();
	}
	
	private List<MessageEntity> parseToList(String jsonString)
	{
		List<MessageEntity> list = new ArrayList();
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(jsonString);
			JSONObject jsonObject;
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				MessageEntity msg = new MessageEntity();
				msg.setMessageid(jsonObject.getString("msgId"));
				msg.setFrom(jsonObject.getString("msgFrom"));
				msg.setDate(jsonObject.getString("msgDate"));
				msg.setMessage(jsonObject.getString("msgBody"));
				list.add(msg);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
